<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" style="margin-bottom: 10px" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="价格编号">
              <a-input v-model="queryParam.serial" placeholder="请输入价格编号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="产品代码">
              <a-input v-model="queryParam.materialCode" dict="hf_custom,name,id" placeholder="请输入产品代码" />
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="产品名称">
              <a-input v-model="queryParam.materialName" placeholder="请输入产品名称" />
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="客户名称">
              <j-search-select-tag
                v-model="queryParam.customId"
                dict="hf_custom,name,id"
                placeholder="请输入客户名称"
                type="list"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="客户品番">
              <a-input v-model="queryParam.saleCode" placeholder="请输入客户品番" />
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="简号">
              <a-input v-model="queryParam.saleCode1" placeholder="请输入简号" style="width: 100%" type="list" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-row>
        <a-button icon="search" type="primary" @click="searchQuery">查询</a-button>
        <a-button icon="reload" type="primary" @click="searchReset">重置</a-button>
        <a-button icon="plus" type="primary" @click="handleAdd">新增</a-button>
        <a-button icon="plus" type="primary" @click="handleOpenBatchAdd">
          批量添加
        </a-button>
      </a-row>
      <a-row>
        <a-button
          v-has="'purchasePrice:import'"
          icon="download"
          type="primary"
          @click="handleExportXlsTemplate('销售价格导入模板')"
          >引出导入模板
        </a-button>
        <a-button icon="download" type="primary" @click="handleExportXls('销售价格方案')">导出全部</a-button>
        <a-upload
          v-has="'salePrice:import'"
          :action="importExcelUrl"
          :headers="tokenHeader"
          :multiple="false"
          :showUploadList="false"
          name="file"
          @change="handleImportExcel"
        >
          <a-button icon="import" type="primary">导入</a-button>
        </a-upload>
        <a-button
          v-has="'salePrice:inputCustom'"
          :loading="inputCustom.loading"
          icon="diff"
          type="primary"
          @click="handleAutoInputCustom"
          >更新无客户的记录
        </a-button>

        <a-button
          icon="import"
          style="background: #FF8F00;border: #FF8F00;"
          type="primary"
          @click="uploadModel.openUpload = true"
          >金蝶导入
        </a-button>
        <a-modal :footer="false" :visible="uploadModel.openUpload" @cancel="() => (uploadModel.openUpload = false)">
          <a-spin :spinning="uploadModel.uploadLoading">
            <a-form :labelCol="{ span: 4 }" :wrapperCol="{ span: 16 }">
              <a-row>
                <a-col :span="24">
                  <a-form-item label="税率">
                    <a-input v-model="uploadModel.tax" placeholder="请输入税率"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="选择文件">
                    <a-upload :customRequest="customUpload" :multiple="false" :showUploadList="false" name="file">
                      <a-button icon="import" style="background: #FF8F00;border: #FF8F00;" type="primary">
                        选择金蝶导出的文件
                      </a-button>
                    </a-upload>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-spin>
        </a-modal>
        <a-button icon="search" type="primary" @click="handleTax">一键更改所有税率</a-button>
        <a-tooltip>
          <template slot="title">
            <span>请先选择在【客户名称】中选择客户</span>
          </template>
          <a-upload
            :action="importFileUrl"
            :data="{
              customId: queryParam.customId,
              priceIds: selectedPriceIds
            }"
            :headers="tokenHeader"
            :multiple="true"
            :show-upload-list="false"
            name="file"
            @change="handleImportExcel"
          >
            <a-button type="primary">
              <a-icon type="upload" />
              上传价格协议
            </a-button>
          </a-upload>
        </a-tooltip>
      </a-row>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination="ipagination"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: true }"
        bordered
        class="j-table-force-nowrap"
        rowKey="id"
        size="middle"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleAddNewPrice(record)">添加新价格</a>
          <a-divider type="vertical" />
          <a @click="handleHistory(record)">历史价格</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record.id)">删除</a>
        </span>
        <span slot="fileSlot" slot-scope="text, record">
          <div v-if="record.priceFile && Object.keys(record.priceFile).length !== 0">
            <a-popover placement="leftBottom" trigger="click">
              <div v-for="(item, index) in record.priceFile" :key="index" slot="content" style="margin-bottom: 5px">
                <a-tooltip>
                  <span slot="title">点击即可打开</span>
                  <a @click="previewFile(item)">价格协议{{ index }}</a>
                </a-tooltip>
                <a-button style="margin-right: 5px;margin-left: 5px" type="primary" @click="downloadFile(item)"
                  >下载</a-button
                >
                <a-button type="danger" @click="deleteUploadedFile(item, index, record.id)">删除</a-button>
              </div>
              <a-button type="primary">附件</a-button>
            </a-popover>
          </div>
          <div v-else>
            无内容
          </div>
        </span>
      </a-table>
    </div>

    <hf-saleprice-modal ref="modalForm" @ok="modalFormOk"></hf-saleprice-modal>
    <HfSalepriceHistoryModal ref="HfSalepriceHistoryModal"></HfSalepriceHistoryModal>
    <HandleSaleTaxModal ref="HandleSaleTaxModal"></HandleSaleTaxModal>
    <HfBatchAddSalePrice ref="HfBatchAddSalePriceRef" @ok="handleBatchAddOk" />
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HfSalePriceModal from './modules/HfSalePriceModal.vue'
import HfSalePriceHistoryModal from './modules/HfSalePriceHistoryModal.vue'
import HandleSaleTaxModal from '@views/sale/modules/HandleSaleTaxModal.vue'
import { deleteAction, getAction, postAction } from '@api/manage'
import { Modal } from 'ant-design-vue'
import HfBatchAddSalePrice from '@views/sale/modules/HfBatchAddSalePrice.vue'

export default {
  name: 'HfSalepriceList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    HfBatchAddSalePrice,
    HandleSaleTaxModal,
    HfSalepriceModal: HfSalePriceModal,
    HfSalepriceHistoryModal: HfSalePriceHistoryModal
  },
  data() {
    return {
      description: '销售价格方案管理页面',
      uploadModel: {
        openUpload: false,
        uploadLoading: false,
        tax: 13
      },
      inputCustom: {
        loading: false
      },
      queryParam: {},
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '价格编号',
          align: 'center',
          dataIndex: 'serial'
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '单价',
          align: 'center',
          dataIndex: 'price'
        },
        {
          title: '税率',
          align: 'center',
          dataIndex: 'tax',
          customRender: r => {
            return r + '%'
          }
        },
        {
          title: '含税单价',
          align: 'center',
          dataIndex: 'taxPrice'
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customId_dictText'
        },
        {
          title: '客户品番',
          align: 'center',
          dataIndex: 'saleCode'
        },
        {
          title: '简号',
          align: 'center',
          dataIndex: 'saleCode1'
        },
        {
          title: 'QAD',
          align: 'center',
          dataIndex: 'qad'
        },
        {
          title: '执行时间',
          align: 'center',
          dataIndex: 'useTime'
        },
        {
          title: '附件',
          align: 'center',
          dataIndex: 'priceFile',
          scopedSlots: { customRender: 'fileSlot' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/sale/hfSalePrice/list',
        delete: '/sale/hfSalePrice/delete',
        deleteBatch: '/sale/hfSalePrice/deleteBatch',
        exportXlsUrl: '/sale/hfSalePrice/exportXls',
        exportXlsTemplateUrl: '/sale/hfSalePrice/exportXlsTemplate',
        importExcelUrl: 'sale/hfSalePrice/importExcelByJD',
        importFileUrl: 'sale/hfSalePrice/importFile',
        deleteUploadedFileUrl: 'sale/hfSalePrice/deleteUploadedFile',
        autoInputCustomUrl: '/sale/hfSalePrice/autoInputCustom'
      },
      dictOptions: {},
      superFieldList: []
    }
  },
  created() {},
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    importFileUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importFileUrl}`
    },
    selectedPriceIds: function() {
      let ids = ''
      if (this.selectedRowKeys.length > 0) {
        ids = this.selectedRowKeys.join(',')
      }
      return ids
    }
  },
  methods: {
    customUpload(options) {
      this.uploadModel.uploadLoading = true
      let { file } = options
      const formData = new FormData()
      formData.append('file', file)
      formData.append('tax', this.uploadModel.tax)
      postAction(this.importExcelUrl, formData, { headers: this.tokenHeader, timeout: 0 })
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .catch(err => {
          console.log('err', err)
        })
        .finally(() => {
          this.uploadModel.openUpload = false
          this.uploadModel.uploadLoading = false
        })
    },
    previewFile(fileUrl) {
      window.open(fileUrl, '_blank')
    },
    handleTax() {
      this.$refs.HandleSaleTaxModal.visible = true
    },
    handleHistory(record) {
      this.$refs.HfSalepriceHistoryModal.open(record)
    },
    handleAddNewPrice(record) {
      this.$refs.modalForm.addNewPrice(record)
      this.$refs.modalForm.title = '添加新价格'
      this.$refs.modalForm.disableSubmit = false
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      params['isDelete'] = 0
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((record, index) => {
              record.priceFile = JSON.parse(record.priceFile)
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    deleteUploadedFile(item, index, id) {
      Modal.confirm({
        title: '确认删除',
        content: '是否删除已上传的文件?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          let param = {
            fileUrl: item,
            fileKey: index,
            priceId: id
          }
          deleteAction(this.url.deleteUploadedFileUrl, param).then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.loadData()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    downloadFile(item) {
      fetch(item)
        .then(response => response.blob())
        .then(blob => {
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          let fileName = item.split('/')[item.split('/').length - 2]
          link.download = fileName
          link.click()
          link.addEventListener('click', function(e) {
            e.preventDefault()
            window.URL.revokeObjectURL(link.href)
          })
        })
        .catch(e => console.error('Download error:', e))
    },
    handleAutoInputCustom() {
      getAction(this.url.autoInputCustomUrl, {}, { timeout: 0 }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleOpenBatchAdd() {
      this.$refs.HfBatchAddSalePriceRef.visible = true
    },
    handleBatchAddOk() {
      this.loadData()
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
